package com.zdlee.netty.server17.server.handler;

import com.zdlee.netty.server17.protocol.request.JoinGroupRequestPacket;
import com.zdlee.netty.server17.protocol.response.JoinGroupResponsePacket;
import com.zdlee.netty.server17.util.SessionUtil;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.group.ChannelGroup;

/**
 * @author zdlee
 * @description: ${DESCRIPTION}
 * @create 2018-12-01 15:37
 */
public class JoinGroupRequestHandler  extends SimpleChannelInboundHandler<JoinGroupRequestPacket> {
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, JoinGroupRequestPacket msg) throws Exception {
        // 1. 获取群对应的 channelGroup，然后将当前用户的 channel 添加进去
        String groupId=msg.getGroupId();
        ChannelGroup channelGroup= SessionUtil.getChannelGroup(groupId);
        channelGroup.add(ctx.channel());

        // 2. 构造加群响应发送给客户端
        JoinGroupResponsePacket responsePacket=new JoinGroupResponsePacket();

        responsePacket.setSuccess(true);
        responsePacket.setGroupId(groupId);
        ctx.channel().writeAndFlush(responsePacket);

    }
}
